﻿using System;
using System.Linq;
using System.Threading;
using System.Windows;
using Microsoft.Phone.BackgroundAudio;
using WindowsPhoneAudioStreaming.Audio.Streaming;

namespace Samples.Radio.Agent.Data
{
    public class Repository
    {
        public static Repository LoadInBackground()
        {
            Repository repository = null;
            var waiter = new ManualResetEvent(false);
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                var dict = new ResourceDictionary
                               {
                    //Use the to access the configuration.xaml file
                                   Source = new Uri("/Samples.Radio;component/Configuration.xaml", UriKind.RelativeOrAbsolute)
                };
                repository = new Repository {Configuration = dict["Configuration"] as ConfigurationSetup};
                waiter.Set();
            });
            waiter.WaitOne();
            return repository;
        }

        public ConfigurationSetup Configuration { get; set; }

        public AudioStreamDefinition CurrentStream
        {
            get
            {
                var streamName = RadioSettings.Instance.CurrentStreamName;
                if(string.IsNullOrWhiteSpace(streamName))
                {
                    streamName = Configuration.Streams.First().Title;
                    RadioSettings.Instance.CurrentStreamName = streamName;
                }
                return Configuration.Streams.First(s => s.Title == streamName);
            }
            set
            {
                if (value != null)
                {
                    if (RadioSettings.Instance.CurrentStreamName == value.Title) return;
                    //                     if (_CurrentPlaybackMode == PlaybackMode.Streaming
                    //            && _CurrentStream != null
                    //            && _CurrentStream.TrackName != value.TrackName)
                    //        {
                    if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                    {
                        //Need to reset the background audio player
                        BackgroundAudioPlayer.Instance.Stop();
                        BackgroundAudioPlayer.Instance.Close();

                        // Now start the player with the new stream
                        BackgroundAudioPlayer.Instance.Play();
                    }
                    //                }

                    RadioSettings.Instance.CurrentStreamName = value.Title;
                }
            }
        }

       
    }
}
